package com.sxl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sxl.config.LayUiResult;
import com.sxl.domain.Message;
import com.sxl.domain.Students;
import com.sxl.mapper.StudentsMapper;
import com.sxl.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: CRMProject
 * @Package: com.sxl.controller
 * @Author songxueliang
 * @Date 2022/5/2 14:32
 */
@RequestMapping("/message")
@RestController
@CrossOrigin
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private StudentsMapper studentsMapper;
    /**
     * 全查消息
     * @param message
     * @return
     */
    @GetMapping("/selectAllMessage")
    public Map<String,Object> selectAllMessage(Message message){
        List<Message> list = messageService.selectAllByReceiverId(message);
        int count = messageService.getCount(message);
        return LayUiResult.toClient("0","成功",count,list);
    }

    /**
     * 设为已读
     * @param id
     * @return
     */
    @PostMapping("updateRead")
    public Map<String ,Object> updateRead(Integer id){
        UpdateWrapper<Message> wrapper = new UpdateWrapper<>();
        wrapper.set("isRead",1).eq("id",id);
        boolean update = messageService.update(wrapper);
        return update==true?LayUiResult.toClient("0","修改成功"):LayUiResult.toClient("1","修改失败");
    }

    /**
     * 发消息
     * @param message
     * @return
     */
    @PostMapping("/sendMessage")
    public Map<String,Object> sendMessage(Message message){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dqsj = df.format(new Date());
        Students students = studentsMapper.selectById(message.getId());
        Message m = new Message();
        m.setContent(message.getContent());
        m.setSenderId(message.getSenderId());
        m.setSenderName(message.getSenderName());
        m.setReceiverId(students.getAskerId());
        m.setReceiverName(students.getZiXunName());
        m.setSendTime(dqsj);
        m.setIsRead(2);
        return messageService.save(m)?LayUiResult.toClient("0","发送成功"):LayUiResult.toClient("1","发送失败");
    }
    /**
     * 查询未读消息
     * @param
     * @return
     */
    @GetMapping("getIsNoReadMessage")
    public boolean getIsNoReadMessage(Integer userId){
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receiverId",userId).eq("isRead",2);
        return messageService.count(queryWrapper) > 0 ? true : false;
    }
}
